<?php

namespace api\models;

use Exception;
use Yii;
use yii\base\Model;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;

class UploadForm extends Model
{
    /**
     * @var UploadedFile[]
     */
    public $imgs;
    public $audios;
    public $videos;
    public $docs;
    public $file;
    public $files;

    public function rules()
    {
        return [
            [['imgs'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg', 'maxFiles' => 4],
            [['audios'], 'file', 'skipOnEmpty' => true, 'maxFiles' => 4],
            [['videos'], 'file', 'skipOnEmpty' => true, 'maxFiles' => 4],
            [['docs'], 'file', 'skipOnEmpty' => true, 'maxFiles' => 4],
            [['file'], 'file', 'skipOnEmpty' => true, 'maxFiles' => 1],
            [['files'], 'file', 'skipOnEmpty' => true, 'maxFiles' => 4],
        ];
    }

    public function upload($delete = true)
    {
        $filePath = Yii::$app->getRuntimePath() . DIRECTORY_SEPARATOR .'uploads' . DIRECTORY_SEPARATOR;
        FileHelper::createDirectory($filePath);
        if ($this->validate()) {
            foreach ($this->imgs as $file) {
                $file->saveAs($filePath . $file->baseName . '.' . $file->extension, $delete);
            }
            foreach ($this->audios as $file) {
                $file->saveAs($filePath . $file->baseName . '.' . $file->extension, $delete);
            }
            foreach ($this->videos as $file) {
                $file->saveAs($filePath . $file->baseName . '.' . $file->extension, $delete);
            }
            foreach ($this->docs as $file) {
                $file->saveAs($filePath . $file->baseName . '.' . $file->extension, $delete);
            }
            return true;
        } else {
            throw new Exception(json_encode($this->getErrors()));
        }
    }
}